﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Gravatar
{
    public static class MD5
    {
        public static string Encode(string s)
        {
            Byte[] originalBytes;
            Byte[] encodedBytes;
            System.Security.Cryptography.MD5 md5 =
                new System.Security.Cryptography.MD5CryptoServiceProvider();
            originalBytes = UTF8Encoding.Default.GetBytes(s);
            encodedBytes = md5.ComputeHash(originalBytes);

            System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder();
            foreach (byte b in encodedBytes)
            {
                stringBuilder.Append(b.ToString("x2").ToLower());
            }

            return stringBuilder.ToString();
        }
    }

    public static class Gravatar
    {
        public static string GetGravatarUrl(string email)
        {
            return GetGravatarUrl(email, 80,"");
        }

        public static string GetGravatarUrl(String email, int size)
        {
            return GetGravatarUrl(email, size, "");
        }

        public static string GetGravatarUrl(String email, int size, String defaultGravatar)
        {
            if (size > 512)
                size = 512;
            if (size < 0)
                size = 1;

            string address =
                "http://www.gravatar.com/avatar.php?gravatar_id="
                + MD5.Encode(email) + "&size=" + size.ToString();
            if (defaultGravatar != "")
            {
                address += "&default=" + defaultGravatar;
            }
            return address;
        }
    }
}
